package com.example.demo.controller;

import com.example.demo.model.Tutorial;
import com.example.demo.service.TutorialRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping(value = "/api")
public class TutorialController {

    @Autowired
    private TutorialRepository tutorialRepository;

    @GetMapping(value = "/tutorials",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<List<Tutorial>> getAllTutorials(@RequestParam(value = "title",required = false) final String title){
        List<Tutorial> tutorials = new ArrayList<>();
        try {
            if (title == null) {
                tutorials = tutorialRepository.findAll();
            }else{
                tutorials = tutorialRepository.findByTitleContains(title);
            }
        } catch (Exception e) {
            return new ResponseEntity<>(null,HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<>(tutorials, HttpStatus.OK);
    }

    @GetMapping(value = "/tutorial/{id}",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Tutorial> getTutorialById(@PathVariable("id") final Long id){
        Optional<Tutorial> tutorialOptional = tutorialRepository.findById(id);
        if (tutorialOptional.isPresent()) {
            return new ResponseEntity<>(tutorialOptional.get(),HttpStatus.OK);
        }
        return new ResponseEntity<>(null,HttpStatus.OK);
    }

    @PostMapping(value = "/tutorial",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Tutorial> saveTutorial(@RequestBody Tutorial tutorial){
        try {
            tutorial = tutorialRepository.save(tutorial);
        } catch (Exception e) {
            return new ResponseEntity<>(null,HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<>(tutorial,HttpStatus.OK);
    }

    @PutMapping(value = "/tutorial",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Tutorial> putTutorial(@RequestBody Tutorial tutorial){
        Optional<Tutorial> entityOptional = tutorialRepository.findById(tutorial.getId());
        if (entityOptional.isPresent()) {
            Tutorial entity = entityOptional.get();
            entity.setTitle(tutorial.getTitle());
            entity.setDescription(tutorial.getDescription());
            entity.setPublished(tutorial.getPublished());
            entity = tutorialRepository.save(entity);
            return new ResponseEntity<>(entity,HttpStatus.OK);
        }
        return new ResponseEntity<>(null,HttpStatus.OK);
    }
}
